<template>
  <el-dialog :title="$t('flycare.statement.generate_title')" width="50%" :modal="false">
    <el-form
      ref="dataForm"
      :model="dataForm"
      label-position="top"
      :rules="rules"
      label-suffix=":"
    >
      <el-form-item :label="$t('common.customer_name')" prop="customerName">
        <el-input
          v-model="dataForm.customerName"
          autocomplete="off"
          clearable
          :placeholder="$t('common.customer_name')"
          style="width: 100%"
          @focus="openCustomerList"
        />
      </el-form-item>
      <el-form-item :label="$t('flycare.statement.generate_month')" prop="generateMonth">
        <el-date-picker
          v-model="dataForm.generateMonth"
          style="width: 100%"
          :format="'YYYY-MM'"
          :value-format="'YYYYMM'"
          type="month"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item :label="$t('modules.contract.plat')" prop="platCode">
        <el-select
          v-model="dataForm.platCode"
          clearable
          style="width: 100%"
          @change="changePlateCode"
        >
          <el-option
            v-for="item in platOptions"
            :key="item.value"
            :label="$t('contract_plat.' + item.value)"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('modules.contract.billing_method')"
        prop="billingServiceCode"
      >
        <el-select v-model="dataForm.billingServiceCode" clearable style="width: 100%">
          <el-option
            v-for="item in currentPlatOption.billingServiceList"
            :key="item.value"
            :label="$t('flycare.billing_service.' + item.value + '.name')"
            :value="item.value"
          />
        </el-select>
      </el-form-item> </el-form
    ><template #footer>
      <span class="dialog-footer">
        <el-button text @click="closeDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="doGenerate">{{
          $t("common.confirm")
        }}</el-button>
      </span></template
    >
    <customer-list
      ref="customerList"
      v-model="customerListVisible"
      @confirmSelect="confirmSelectCustomer"
    />
  </el-dialog>
</template>
<script>
import { generateStatementByCustomer } from "@/api/statement";
import { findPlatBillingService } from "@/api/module";
import CustomerList from "@/views/service-management/components/customer-list";

export default {
  components: {
    CustomerList,
  },
  data() {
    return {
      confirmLoading: false,
      platOptions: [],
      serviceOptions: [],
      customerListVisible: false,
      currentPlatOption: [],
      dataForm: {
        customerName: "",
        characterCode: "OPERATOR",
        keyId: "",
        platCode: "",
        billingServiceCode: "",
        generateMonth: "",
      },
      rules: {
        customerName: [
          {
            required: true,
            trigger: "change",
            message: this.$t("flycare.input_require.customer_name"),
          },
        ],
        generateMonth: [
          {
            required: true,
            trigger: "change",
            message: this.$t("flycare.input_require.month"),
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getFullYear() * 10 + time.getMonth() >
            new Date().getFullYear() * 10 + new Date().getMonth()
          );
        },
      },
    };
  },
  methods: {
    openDialog() {
      this.getPlatService();
    },
    // 获取platCode
    getPlatService() {
      findPlatBillingService()
        .then((res) => {
          this.platOptions.length = 0;
          for (let i = 0; i < res.length; i++) {
            const billingServiceList = [];
            for (let j = 0; j < res[i].billingServiceList.length; j++) {
              const item = res[i].billingServiceList[j];
              const service = {
                value: item.billingServiceCode,
                label: item.billingServiceName,
                allowFreeNum: item.allowFree,
                freeExpireFlag: item.freeExpireFlag,
                unit: item.serviceAmountUnit,
                expireFlag: item.expireFlag,
                billingType: item.billingType,
                serviceQuantityUnit: item.serviceQuantityUnit,
                startTimeRequire: item.startTimeRequire,
                canRenewal: item.canRenewal,
              };
              billingServiceList.push(service);
            }
            const temp = {
              value: res[i].platCode,
              label: res[i].platCode,
              billingServiceList: billingServiceList,
            };
            this.platOptions.push(temp);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    changePlateCode(val) {
      if (val) {
        this.currentPlatOption = this.platOptions.filter((item) => item.value === val)[0];
        console.log(this.currentPlatOption);
        this.dataForm.billingServiceCode = "";
      }
    },

    confirmSelectCustomer(selectedCustomer) {
      this.dataForm.characterCode = selectedCustomer.characterCode;
      this.dataForm.keyId = selectedCustomer.keyId;
      this.dataForm.customerName = selectedCustomer.name;
    },
    openCustomerList() {
      this.customerListVisible = true;
      this.$nextTick(() => {
        this.$refs.customerList.openDialog();
      });
    },
    doGenerate() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          generateStatementByCustomer(this.dataForm)
            .then((res) => {
              if (res && res.length > 0) {
                const statementMonth =
                  this.dataForm.generateMonth.substring(0, 4) +
                  "-" +
                  this.dataForm.generateMonth.substring(4, 7);
                this.$emit("openGenStatementResult", {
                  genFailedService: res,
                  statementMonth: statementMonth,
                });
              } else {
                this.$message.success(this.$t("common.success"));
              }
              this.$emit("refreshData");
              this.closeDialog();
            })
            .catch((err) => {
              if (err.code === "1009") {
                this.$message.error("Missing reference statistics");
              } else {
                this.$message.error(err.message);
              }
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        }
      });
    },
    closeDialog() {
      this.$emit("update:model-value", false);
      this.$refs.dataForm.resetFields();
    },
  },
};
</script>
